#include "networkmonitor.h"
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QStandardPaths>

NetworkMonitor::NetworkMonitor(QObject *parent)
    : QObject(parent)
    , m_timer(new QTimer(this))
    , m_totalStations(50)
    , m_onlineUsers(1250)
    , m_avgSignalQuality(85.5)
    , m_abnormalStations(0)
    , m_overallStatus("normal")
{
    connect(m_timer, &QTimer::timeout, this, &NetworkMonitor::updateData);
    
    // 初始化信号历史数据 (10分钟 * 60秒 / 2秒 = 300个数据点)
    for (int i = 0; i < 300; ++i) {
        m_signalHistory.append(80.0 + QRandomGenerator::global()->bounded(10));
    }
}

void NetworkMonitor::startMonitoring()
{
    m_timer->start(2000); // 每2秒更新一次
}

void NetworkMonitor::stopMonitoring()
{
    m_timer->stop();
}

void NetworkMonitor::updateData()
{
    // 只模拟在线用户数变化
    int userChange = QRandomGenerator::global()->bounded(101) - 50; // -50 到 50
    m_onlineUsers = qMax(800, qMin(2000, m_onlineUsers + userChange));
    emit onlineUsersChanged();

    // 注意：异常基站数和平均信号质量现在从 BaseStationModel 获取
    // 不再在此处模拟
}

void NetworkMonitor::updateStatus()
{
    QString oldStatus = m_overallStatus;
    
    if (m_abnormalStations >= 3 || m_avgSignalQuality < 60) {
        m_overallStatus = "critical";
    } else if (m_abnormalStations > 0 || m_avgSignalQuality < 75) {
        m_overallStatus = "warning";
    } else {
        m_overallStatus = "normal";
    }
    
    if (oldStatus != m_overallStatus) {
        emit overallStatusChanged();
    }
}

QVariantList NetworkMonitor::getSignalTrendData()
{
    QVariantList result;
    // 只返回数据点，间隔采样以提高性能 (每10个点取1个)
    int sampleInterval = 10;
    for (int i = 0; i < m_signalHistory.size(); i += sampleInterval) {
        QVariantMap point;
        point.insert("x", QVariant(i));
        point.insert("y", QVariant(m_signalHistory[i]));
        result.append(point);
    }
    // 确保最后一个点被包含
    if (m_signalHistory.size() > 0 && (m_signalHistory.size() - 1) % sampleInterval != 0) {
        QVariantMap point;
        point.insert("x", QVariant(m_signalHistory.size() - 1));
        point.insert("y", QVariant(m_signalHistory.last()));
        result.append(point);
    }
    return result;
}

void NetworkMonitor::setStatistics(int abnormalCount, double avgSignal)
{
    bool abnormalChanged = false;
    bool signalChanged = false;
    
    if (m_abnormalStations != abnormalCount) {
        m_abnormalStations = abnormalCount;
        abnormalChanged = true;
    }
    
    if (qAbs(m_avgSignalQuality - avgSignal) > 0.1) { // 避免浮点数比较问题
        m_avgSignalQuality = avgSignal;
        signalChanged = true;
        
        // 添加到历史记录 (保留最近10分钟的数据，300个点)
        m_signalHistory.append(m_avgSignalQuality);
        if (m_signalHistory.size() > 300) {
            m_signalHistory.removeFirst();
        }
    }
    
    if (abnormalChanged) {
        emit abnormalStationsChanged();
    }
    
    if (signalChanged) {
        emit avgSignalQualityChanged();
    }
    
    updateStatus();
}

void NetworkMonitor::setTotalStations(int total)
{
    if (m_totalStations != total) {
        m_totalStations = total;
        emit totalStationsChanged();
    }
}

bool NetworkMonitor::saveReportFile(const QString &fileName, const QString &content)
{
    try {
        // 获取应用程序目录
        QString appDir = QDir::currentPath();
        QString reportsDir = appDir + "/reports";
        
        // 创建 reports 目录（如果不存在）
        QDir dir;
        if (!dir.exists(reportsDir)) {
            if (!dir.mkpath(reportsDir)) {
                qWarning() << "无法创建 reports 目录:" << reportsDir;
                return false;
            }
        }
        
        // 创建完整的文件路径
        QString filePath = reportsDir + "/" + fileName;
        
        // 创建并写入文件
        QFile file(filePath);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qWarning() << "无法打开文件进行写入:" << filePath;
            return false;
        }
        
        QTextStream out(&file);
        out.setEncoding(QStringConverter::Utf8);
        out << content;
        file.close();
        
        qDebug() << "报告已成功保存到:" << filePath;
        return true;
        
    } catch (const std::exception &e) {
        qWarning() << "保存报告文件时发生异常:" << e.what();
        return false;
    } catch (...) {
        qWarning() << "保存报告文件时发生未知异常";
        return false;
    }
}

